/**
 *
 * Created by Song,YeWen, 1/16/2012 4:30:14 PM
 *
 */

function  validateVideoUrl(ori_url) 
{
    //We use a fake constant duration for mtime.com, because it is Movie trailer, not long duration video
    //TODO: FIXME
    var fcduration = '100';
	var html = download_page(ori_url);
	matches = html.match(/vid\s*=\s*(\d+)/);
	if (matches == null) {
	    // try to detect: http://www.smgbb.cn/movies/2011-09-13/416.html
	    // try to detect: http://v.smgbb.cn/dianshiju/2011-12-30/8695.html
	    // TODO: FIXME:
		// vid not found
		return 'NotFoundVideo';
	}	
	// http://www1.smgbb.cn/playxml/statdir/34/playlist961634.xml
	var vid = matches[1];
	var disp_dir = vid.substring(vid.length-2, vid.length);	
	var dst_url = 'http://www1.smgbb.cn/playxml/statdir/' + disp_dir + '/playlist'+ matches[1] + '.xml';
	var xml_str = download_page(dst_url);
	var flv_string = parse_xml_attribute(xml_str,'playing','url');

	//matches = html.match(/<title>(.*?)<\/title>/);
	matches = html.match(/<title>([\s\S]*?)<\/title>/);
	if(matches){
	   return 'success_title:' + encodeURIComponent(matches[1])
	          + '\n video_urls:' + encodeURIComponent(flv_string)
	          + '\n seconds:' + parseInt(fcduration);
	}
    return 'error:empty_path';
}

/* mp4: http://info.smgbb.cn/zixun/yule/2012-01-16/961634.html */
/* flv: http://www.smgbb.cn/movies/2011-09-13/416.html */
/* ts: http://v.smgbb.cn/dianshiju/2011-12-30/8695.html */
function js_get_media_url(ori_url) 
{
	var html = download_page(ori_url);
	matches = html.match(/vid\s*=\s*(\d+)/);
	var media_url = null;
	var vid = null;
	var dst_url = null;
	var xml_str = null;
	if (matches == null) {
	    // mp4: http://www.smgbb.cn/movies/2011-09-13/416.html
	    var flashvars = copyBetween(html,"flashvars=\"","\"");
	    if (flashvars.length > 0) {
	        media_url = copyBetween(flashvars,"file=", "&");
	        if (media_url.length < 6)
	           return '';
	       return media_url;
	    } else {
	        // mpeg-ts: http://v.smgbb.cn/dianshiju/2011-12-30/8695.html
	        vid = copyBetween(html,".swf?id=", "\"");
	        vid = parseInt(vid);
	        // http://v.smgbb.cn/data/video_xml.php?id=31494
	        if (vid <= 0)
	            return '';
	        dst_url = "http://v.smgbb.cn/data/video_xml.php?id=" + vid;
	        xml_str = download_page(dst_url);
	        var index_m3u = parse_xml(xml_str, "videoinfo", "videos", "stream");
	        // TODO: parse m3u8
	        var sb = [];	        
		    // vid not found
		    return '';
	    }
	} else {
	    // http://www1.smgbb.cn/playxml/statdir/34/playlist961634.xml
	    vid = matches[1];
	    var disp_dir = vid.substring(vid.length-2, vid.length);	
	    var dst_url = 'http://www1.smgbb.cn/playxml/statdir/' + disp_dir + '/playlist'+ matches[1] + '.xml';
	    var xml_str = download_page(dst_url);
	    media_url = parse_xml_attribute(xml_str,'playing','url');
	}

	return media_url;
}
